package com.jams.goodox.activity.serve.meet;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hangzhou.jin.customview.TailsTextView;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.activity.ChoosePayActivity;
import com.jams.goodox.activity.common.EditTextActivity;
import com.jams.goodox.activity.home.HomeActivity;
import com.jams.goodox.activity.mine.address.MineAddressActivity;
import com.jams.goodox.activity.serve.ChooseBillManager;
import com.jams.goodox.activity.serve.park.ParkingApplyActivity;
import com.jams.goodox.constant.Constants;
import com.jams.goodox.entity.Address;
import com.jams.goodox.entity.MeetSessionItemBean;
import com.jams.goodox.entity.MeetSureOrderBean;
import com.jams.goodox.entity.ParkOrderItemBean;
import com.jams.goodox.entity.PayInfo;
import com.jams.goodox.entity.PlaceInfoOrderBean;
import com.jams.goodox.entity.RedPacket;
import com.jams.goodox.entity.User;
import com.jams.goodox.entity.resp.AddOrderResp;
import com.jams.goodox.entity.resp.ParkPlaceOrderResp;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.ServiceService;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.MoneyUtils;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.widget.ChooseBillView;
import com.jams.goodox.widget.NoScrollListView;
import com.jams.library.commonAdapter.ListCommonAdapter;
import com.jams.library.commonAdapter.ListCommonViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 场次预定确认订单页
 * Created by jams_zhen on 2017/5/12.
 */

public class MeetPartOrderSureActivity extends BaseActivity implements RetrofitCallbackListener<AddOrderResp> {
    @Bind(R.id.tx_company)
    TextView txCompany;
    @Bind(R.id.tx_address)
    TextView txAddress;
    @Bind(R.id.tx_userName)
    TextView txUserName;
    @Bind(R.id.tx_userTel)
    TextView txUserTel;
    @Bind(R.id.tx_room_name)
    TextView txRoomName;
    @Bind(R.id.list_date)
    NoScrollListView listDate;
    @Bind(R.id.tx_money)
    TextView txMoney;
    @Bind(R.id.tx_needPay)
    TextView txNeedPay;
    @Bind(R.id.tx_red_money)
    TextView txRedMoney;
    @Bind(R.id.iv_onLine)
    ImageView ivOnLine;
    @Bind(R.id.sell_off_tails)
    TailsTextView sellOffTails;
    @Bind(R.id.rl_order_pay_online)
    RelativeLayout rlOrderPayOnline;
    @Bind(R.id.rl_order_pay_outline)
    RelativeLayout rl_order_pay_outline;
    @Bind(R.id.iv_outline)
    ImageView ivOutline;
    @Bind(R.id.tx_go)
    TextView txGo;
    @Bind(R.id.tx_type)
    TextView txType;
    @Bind(R.id.right_arrow)
    ImageView right_arrow;
    @Bind(R.id.sell_off_layout)
    RelativeLayout sell_off_layout;
    @Bind(R.id.tv_order_leave_msg)
    TextView tvOrderLeaveMsg;

    @Bind(R.id.order_sure_name)
    TextView orderSureName;
    @Bind(R.id.order_sure_phone)
    TextView orderSurePhone;
    @Bind(R.id.address)
    TextView address;

    @Bind(R.id.serve_include_address_user)
    LinearLayout serve_include_address_user;
    @Bind(R.id.order_include_user_address)
    LinearLayout order_include_user_address;

    @Bind(R.id.scrollView)
    ScrollView scrollView;
    @Bind(R.id.choose_bill_view)
    ChooseBillView chooseBillView;
    @Bind(R.id.linear_pay_red_layout)
    LinearLayout linear_pay_red_layout;

    private MeetSureOrderBean.Data meetSureData;//场地预定实体
    private ParkPlaceOrderResp.DataBean parkSureBean;//停车申请实体
    private int fromType;//表示传入的类型
    private Intent in;

    private double totalMoney;//合计金额
    private double needPayMoney;//应付金额
    private RedPacket redPacket;//红包
    private String shopperName;//商家名称
    private String payType;//支付方式 0线上 1线下  2线上线下
    private String choosePayType;

    private boolean hasRedPacket;//是否有红包

    private String subId;

    private String markContent;

    private String busId;

    private boolean isCompanyOrder;//是否是企业订单

    private User user;
    private Address userAddress;

    public static final String Type_Comment="1";
    public static final String Type_Special="2";

    private ChooseBillManager chooseBillManager;

    public static void startFromMeet(Context context, MeetSureOrderBean.Data bean, int type, String subId,String busId) {
        Intent in = new Intent(context, MeetPartOrderSureActivity.class);
        in.putExtra("bean", bean);
        in.putExtra("type", type);
        in.putExtra("subId", subId);
        in.putExtra("busId",busId);
        context.startActivity(in);
    }

    public static void startFromPark(Context context, ParkPlaceOrderResp.DataBean bean, int type, String subId, String busId, boolean isCompanyOrder) {
        Intent in = new Intent(context, MeetPartOrderSureActivity.class);
        in.putExtra("bean", bean);
        in.putExtra("type", type);
        in.putExtra("subId", subId);
        in.putExtra("busId", busId);
        in.putExtra("isCompanyOrder", isCompanyOrder);
        context.startActivity(in);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.meet_order_sure_activity;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this, "确认订单");
        getData();
    }

    private void getData() {
        user=DataCacheManager.getInstance().getUser();
        in = getIntent();
        fromType = in.getIntExtra("type",0);
        subId = in.getStringExtra("subId");
        busId=in.getStringExtra("busId");
        isCompanyOrder = in.getBooleanExtra("isCompanyOrder", true);//默认企业订单
        if (fromType==0) return;
        switch (fromType) {
            case Constants.MEET_CODE://会议类型确认订单
                meetSureData = (MeetSureOrderBean.Data) in.getSerializableExtra("bean");
                txType.setText("场地预订");
                shopperName = "场地预订";
                totalMoney = meetSureData.getScheduleOrder().getTotal();
                redPacket = meetSureData.getRedPacket();
                payType = meetSureData.getSubPayType();
                tvOrderLeaveMsg.setHint("请描述你的要求…");
                setMeetList();
                break;
            case Constants.PARKING_CODE:
                txType.setText("停车申请");
                shopperName = "停车申请";
                parkSureBean = (ParkPlaceOrderResp.DataBean) in.getSerializableExtra("bean");
                totalMoney = parkSureBean.getPlaceInfoOrder().getOrderMoneyTotal();
                redPacket = parkSureBean.getRedPacket();
                payType = parkSureBean.getSubPayType();
                tvOrderLeaveMsg.setHint("给服务商留言…");
                setPartList();
                break;
        }
        setCommentData();
        if(totalMoney==0&&fromType==Constants.MEET_CODE){//场地预定，免费场地不现实发票内容
            chooseBillView.setVisibility(View.GONE);
            linear_pay_red_layout.setVisibility(View.GONE);
        }else {
            chooseBillView.setVisibility(View.VISIBLE);
            chooseBillManager=new ChooseBillManager(this,isCompanyOrder,busId,chooseBillView);
        }
    }

    /**
     * 设置场地预定的列表
     */
    private void setMeetList() {
        List<MeetSessionItemBean> meetSessionItemBeanList = meetSureData.getScheduleOrder().getScheduleList();
        if (meetSessionItemBeanList == null || meetSessionItemBeanList.size() == 0) return;
        txRoomName.setText(meetSessionItemBeanList.get(0).getAddress());
        listDate.setAdapter(new ListCommonAdapter<MeetSessionItemBean>(this, meetSessionItemBeanList, R.layout.item_meet_sure_order) {
            @Override
            public void convert(ListCommonViewHolder helper, MeetSessionItemBean item, int position) {
                helper.setText(R.id.tx_time, String.format("%s %s", meetSureData.getPlaceDate(), item.getSessionDurationTime()));
                helper.setText(R.id.tx_pre_pay, item.getShowPriceUnitNumber());
            }
        });
    }

    /**
     * 设置停车申请的列表
     */
    private void setPartList() {
        PlaceInfoOrderBean placeInfoOrderBean = parkSureBean.getPlaceInfoOrder();
        txRoomName.setText(placeInfoOrderBean.getCarNum());

        ParkOrderItemBean parkOrderItemBean = new ParkOrderItemBean();
        String unit;
        if (ParkingApplyActivity.Type_Menu_Month == placeInfoOrderBean.getMenuType()) {
            unit = "月";
        } else {
            unit = "年";
        }
        parkOrderItemBean.priceUnit = String.format("%s元/%s", (int) placeInfoOrderBean.getMenuCost(), unit);
        parkOrderItemBean.number = String.format("x%s", placeInfoOrderBean.getBuyNum());
        parkOrderItemBean.useTime = String.format("%s~%s", placeInfoOrderBean.getStartTime(), placeInfoOrderBean.getEndTime());
        List<ParkOrderItemBean> beanList = new ArrayList<>();
        beanList.add(parkOrderItemBean);

        listDate.setAdapter(new ListCommonAdapter<ParkOrderItemBean>(this, beanList, R.layout.item_place_order) {
            @Override
            public void convert(ListCommonViewHolder helper, ParkOrderItemBean item, int position) {
                helper.setText(R.id.tx_park_price_num, item.priceUnit);
                helper.setText(R.id.tx_park_number, item.number);
                helper.setText(R.id.tx_date_time, item.useTime);
            }
        });
    }

    /**
     * 设置通用数据：头部，应付，待付，红包，支付方式
     */
    private void setCommentData() {
        setUserInfo();
        sell_off_layout.setVisibility(View.GONE);
        txMoney.setText(MoneyUtils.withSpaceMoney(totalMoney));
        setRedPacket();
        txNeedPay.setText(User.getPriceStyle(needPayMoney, ""));
        setPayType();
    }

    /**
     * 配置线上线下支付方式
     */
    private void setPayType() {
        if (TextUtils.isEmpty(payType)) return;
        switch (payType) {
            case Constants.PayType_OutLine:
                rlOrderPayOnline.setVisibility(View.GONE);
                rl_order_pay_outline.setVisibility(View.VISIBLE);
                setPayType(Constants.PayType_OutLine);
                break;
            case Constants.PayType_OnLine:
                rlOrderPayOnline.setVisibility(View.VISIBLE);
                rl_order_pay_outline.setVisibility(View.GONE);
                setPayType(Constants.PayType_OnLine);
                break;
            case Constants.PayType_All:
                rlOrderPayOnline.setVisibility(View.VISIBLE);
                rl_order_pay_outline.setVisibility(View.VISIBLE);
                setPayType(Constants.PayType_OnLine);
                break;
        }
    }

    /**
     * 设置红包
     * 1：线下支付，不显示红包及右侧箭头
     * 2：选择的红包或者红包金额为0
     *   2.1：有红包情形：显示不使用红包，可选择红包（此处如果提交接口返回红包，表示有可用红包，若不返回，就无法选择红包）
     *   2.2：无红包情况：红包不显示，箭头隐藏，不可选
     * 3：选择了红包，且金额>0
     *    3.1：红包金额>=订单金额，应付金额为0
     *    3.2：应付金额显示两者差值
     */
    private void setRedPacket() {
        if (Constants.PayType_OutLine.equalsIgnoreCase(choosePayType)) {
            txRedMoney.setVisibility(View.GONE);
            right_arrow.setVisibility(View.GONE);
            return;
        }
        if (redPacket == null || redPacket.getMoney() == null||(totalMoney==0&&fromType==Constants.MEET_CODE)) {//新增需求，场地预定，总金额=0，按红包为0处理）
            txRedMoney.setVisibility(View.GONE);
            right_arrow.setVisibility(View.GONE);
            if (hasRedPacket) {
                txRedMoney.setVisibility(View.VISIBLE);
                right_arrow.setVisibility(View.VISIBLE);
                txRedMoney.setText("不使用红包");
                txRedMoney.setTextColor(ContextCompat.getColor(this, R.color.font_color_gray));
                txRedMoney.setCompoundDrawables(null, null, null, null);
            }
            needPayMoney = totalMoney;
            txNeedPay.setText(User.getPriceStyle(needPayMoney, ""));
        } else {
            hasRedPacket = true;
            if (totalMoney < redPacket.getMoney()) {
                txNeedPay.setText(User.getPriceStyle(0.00, ""));
                needPayMoney = 0.00;
            } else {
                needPayMoney = totalMoney - redPacket.getMoney();
                txNeedPay.setText(User.getPriceStyle(needPayMoney, ""));
            }
            txRedMoney.setVisibility(View.VISIBLE);
            right_arrow.setVisibility(View.VISIBLE);
            txRedMoney.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.red_packet_icon, 0, 0, 0);
            txRedMoney.setText(User.getPriceStyle(redPacket.getMoney(), ""));
            txRedMoney.setTextColor(ContextCompat.getColor(this, R.color.red));
        }

    }

    private void setPayType(String payType) {
        this.choosePayType = payType;
        switch (choosePayType) {
            case Constants.PayType_OnLine:
                ivOnLine.setImageResource(R.mipmap.check_price_icon);
                ivOutline.setImageResource(R.mipmap.uncheck_icon);
                setRedPacket();//每次选择线上支付，都需要重新处理应付，红包等信息
                break;
            case Constants.PayType_OutLine:
                ivOnLine.setImageResource(R.mipmap.uncheck_icon);
                ivOutline.setImageResource(R.mipmap.check_price_icon);
                txRedMoney.setVisibility(View.GONE);
                right_arrow.setVisibility(View.GONE);
                needPayMoney = totalMoney;
                txNeedPay.setText(User.getPriceStyle(needPayMoney, ""));
                break;
            default:
                break;
        }
    }

    @OnClick({R.id.rl_order_pay_online, R.id.rl_order_pay_outline, R.id.red_packet, R.id.tx_go, R.id.tv_order_leave_msg, R.id.tx_red_money,
            R.id.lv_simple_group, R.id.lv_special_group, R.id.relative_company_bill, R.id.relative_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_order_pay_online:
                setPayType(Constants.PayType_OnLine);
                break;
            case R.id.rl_order_pay_outline:
                setPayType(Constants.PayType_OutLine);
                break;
            case R.id.tx_red_money:
                break;
            case R.id.tx_go:
                if (fromType==Constants.MEET_CODE) {
                    submitMeetOrder();
                } else {
                    submitParkOrder();
                }
                break;
            case R.id.tv_order_leave_msg:
                in.setClass(this, EditTextActivity.class);
                in.putExtra(EditTextActivity.ETITLE, "备注");
                in.putExtra(EditTextActivity.ERIGHT, getString(R.string.confirm));
                if (!TextUtils.isEmpty(markContent)) in.putExtra(EditTextActivity.ECONTENT, markContent);
                if(fromType==Constants.MEET_CODE){
                    in.putExtra(EditTextActivity.EHINT, getString(R.string.meet_mark_hint));
                }else {
                    in.putExtra(EditTextActivity.EHINT, "给服务商留言...");
                }
                startActivityForResult(in, 1993);
                break;
            case R.id.relative_address:
                if (isCompanyOrder) return;
                Intent in = new Intent(this, MineAddressActivity.class);
                if (!User.isAddressExit(userAddress))
                    in.putExtra("id", userAddress.getId());
                startActivityForResult(in, 122);
                break;
        }
    }

    /**
     * 设置头部信息
     */
    private void setUserInfo() {
        if (!isCompanyOrder) {
            order_include_user_address.setVisibility(View.VISIBLE);
            serve_include_address_user.setVisibility(View.GONE);

            orderSureName.setText(user.getUserName());
            orderSurePhone.setText(user.getMobileNum());
            userAddress=user.getAddress();
            address.setText(TextUtils.isEmpty(userAddress.getAddressDetail())?"":userAddress.getAddressDetail());
        } else {
            order_include_user_address.setVisibility(View.GONE);
            serve_include_address_user.setVisibility(View.VISIBLE);

            txUserName.setText(user.getUserName());
            txUserTel.setText(user.getMobileNum());
            txAddress.setText(user.getEnterpriseAddress());
            txCompany.setText(user.getEnterpriseName());
        }
    }

    private void submitMeetOrder() {
        if (meetSureData == null) return;
        MeetSureOrderBean.ScheduleOrderBean orderBean = meetSureData.getScheduleOrder();
        if (redPacket != null && !TextUtils.isEmpty(redPacket.getRedPacketId()))
            orderBean.setRedPacketId(redPacket.getRedPacketId());
        if (!TextUtils.isEmpty(markContent)) orderBean.setRemark(markContent);
        orderBean.setSubPayType(Constants.getMoneyPayTypeBySubPayType(choosePayType));
        orderBean.setBusId(busId);
        if (chooseBillManager!=null&&!"0".equalsIgnoreCase(chooseBillManager.getInvoiceType()))
            orderBean.setInvoiceType(chooseBillManager.getInvoiceType());
        String orderBeanStr = new Gson().toJson(orderBean);
        showLoading();
        enqueue(createCallService(ServiceService.class).addMeetOrder(orderBeanStr), this);
    }

    /**
     * 提交停车申请订单：个人下单，可能收货地址为空
     */
    private void submitParkOrder() {
        if (parkSureBean == null || parkSureBean.getPlaceInfoOrder() == null) return;
        if(!isCompanyOrder&&!User.isAddressExit(userAddress)){//个人订单，且未获得收货地址，退出
            ToastUtil.show("请设置收货地址");
            return;
        }
        PlaceInfoOrderBean placeInfoOrderBean = parkSureBean.getPlaceInfoOrder();
        if (redPacket != null && !TextUtils.isEmpty(redPacket.getRedPacketId()))
            placeInfoOrderBean.setRedPacketId(redPacket.getRedPacketId());
        if (!TextUtils.isEmpty(markContent)) placeInfoOrderBean.setOrderRemark(markContent);
        placeInfoOrderBean.setBusId(busId);
        if (chooseBillManager!=null&&!"0".equalsIgnoreCase(chooseBillManager.getInvoiceType())){
            placeInfoOrderBean.setInvoiceType(chooseBillManager.getInvoiceType());
            placeInfoOrderBean.setInvoiceName(chooseBillManager.getInvoiceName());
        }
        placeInfoOrderBean.setMoneyType(Constants.getMoneyPayTypeBySubPayType(choosePayType));

        String addressStr = isCompanyOrder?user.getEnterpriseAddress():userAddress.getAddressDetail();
        placeInfoOrderBean.setEnterpriseHouseName(addressStr);

        String orderBeanStr = new Gson().toJson(placeInfoOrderBean);
        showLoading();
        enqueue(createCallService(ServiceService.class).addOrder(orderBeanStr), this);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1994:
                if (resultCode == 1) {
                    if (data != null) {
                        redPacket = (RedPacket) data.getSerializableExtra("redPacket");
                        setRedPacket();
                    }
                } else if (resultCode == 2) {
                    //返回不使用红包
                    redPacket = null;
                    setRedPacket();
                }
                break;
            case 1993:
                if (resultCode == 100) {
                    if (data != null) {
                        markContent = data.getStringExtra(EditTextActivity.ECONTENT);
                        tvOrderLeaveMsg.setText(markContent);
                    }
                }
                break;
            case 1991:
                chooseBillManager.getMyInvoice();
                break;
            case 122:
                if (resultCode == 1) {
                    if (data != null) {
                        userAddress = (Address) data.getSerializableExtra("bean");
                        if (userAddress == null) return;
                        address.setText(userAddress.getAddressDetail());
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onSuccess(Call<AddOrderResp> call, AddOrderResp result) {
        misLoading();
        ToastUtil.show("提交成功");
        PayInfo payInfo = result.getData();
        if (payInfo == null) return;
        if (Constants.PayType_OutLine.equalsIgnoreCase(choosePayType) || needPayMoney <= 0) {//无需支付（可能使用红包抵扣等）
            Intent intent = new Intent(MeetPartOrderSureActivity.this, HomeActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
            setResult(1992);//付款成功后回调
            finish();
        } else {
            Intent intent = new Intent(MeetPartOrderSureActivity.this, ChoosePayActivity.class);
            intent.putExtra("come", 1);
            if (isCompanyOrder) {//企业订单时，传递企业订单类型对应值2
                payInfo.setOrderCreateClassfiy(2);
            }else {
                payInfo.setOrderCreateClassfiy(1);
            }
            payInfo.setPaySubCode(fromType);//企业余额支付需要获取对应类型，支付成功需要获取对应类型
            payInfo.setServerName(shopperName);
            payInfo.setOrderAllMoney(totalMoney);
            payInfo.setThirdPayConfigType(fromType == Constants.MEET_CODE ? Constants.PayType.Type_Meet : Constants.PayType.Type_Parking);
//            intent.putExtra("onlinePayDiscount", 10.0);//折扣默认10折，可不传
            if (redPacket != null && redPacket.getMoney() != 0)
                payInfo.setRedPacketMoney(redPacket.getMoney());
            intent.putExtra("payInfo", result.getData());
            startActivity(intent);
            finish();
        }
    }

    @Override
    public void onError(String msg) {
        misLoading();
        ToastUtil.show(msg);
    }
}
